<template>
  <div class="digit-input">
      <div>
        <span>数字输入框:</span>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <input type="text"
          :value="value"
          v-bind="$attrs"
          @compositionstart="handleCompositionStart"
          @compositionend="handleCompositionEnd"
          @input="fnValueChange" />
          <h4>
            非英文状态下目前发现的问题已解决，详情可见
            <router-link to="/transmit">Transmit</router-link>
          </h4>
      </div>
      <hr>
      <digit-wrapper v-model="number" maxlength="10" @focus="onFocus" placeholder="默认提示"></digit-wrapper>
      <hr>
  </div>
</template>

<script>
import DigitWrapper from '@/components/DigitWrapper.vue'

export default {
  inheritAttrs: false,
  name: 'DigitInput',
  props: {
    value: [String, Number]
  },
  data () {
    return {
      message: '处理边界情况',
      number: '4',
      decimal: 2,
      isComposing: false
    }
  },
  components: {
    DigitWrapper
  },
  computed: {
    // 定义事件，并且排除我们需要处理的input事件，v-on通过对象绑定事件可以和单独绑定同名事件共存，并且两者都生效
    events () {
      const ret = {}
      Object.keys(this.$listeners).forEach(key => {
        if (key !== 'input') {
          ret[key] = this.$listeners[key]
        }
      })
      return ret
    }
  },
  methods: {
    handleCompositionStart () {
      this.isComposing = true
    },
    handleCompositionEnd ($event) {
      if (this.isComposing) {
        this.isComposing = false
        this.fnValueChange($event)
      }
    },
    fnValueChange ($event) {
      if (this.isComposing) return
      const value = $event.target.value
      const regexp = new RegExp(`^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,${this.decimal}})?$`)
      if (regexp.test(value) || value === '') {
        this.$emit('input', $event.target.value)
      }
      this.$nextTick(() => {
        $event.target.value = this.value === null || this.value === undefined ? '' : String(this.value)
      })
    },
    onFocus () {
      console.log('focus 触发')
    }
  }
}
</script>
